<?php
global $argv;

// 获取命令行中的参数
use Xin\Support\Str;

$commandQueueWorkList = (function () use ($argv) {
    $queueWorkStr = array_find('queue:work', $argv);
    if (!$queueWorkStr) {
        return [];
    }

    $err = new InvalidArgumentException("无效的参数[queue:work]，请检查参数格式[queue:work=default,...]");
    $queueWorks = explode("=", $queueWorkStr, 2);
    if (count($queueWorks) !== 2) {
        throw $err;
    }

    $queueWorks = explode(",", $queueWorks[1]);
    return array_filter($queueWorks);
})();

$defaultQueueName = env('QUEUE_DEFAULT', 'default');
$queueWorkList = env('QUEUE_WORK_LIST', '');
$queueWorkList = array_filter(explode(",", $queueWorkList));
$queueWorkList = array_merge($queueWorkList, $commandQueueWorkList);
$queueWorkList = array_reduce($queueWorkList, function ($result, $item) {
    $item = explode(":", $item, 2);
    $result[$item[0]] = (int)($item[1] ?? 1);
    return $result;
}, []);

// 最终配置
$config = [];
foreach ($queueWorkList as $workName => $workCount) {
    $config[$workName] = [
        'handler' => Webman\RedisQueue\Process\Consumer::class,
        'count' => $workCount, // 可以设置多进程同时消费
        'constructor' => [
            // 消费者类目录
            'consumer_dir' => app_path() . DIRECTORY_SEPARATOR . 'queue' . DIRECTORY_SEPARATOR . Str::plural($workName),
        ],
    ];
}

return $config;
